import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Layout, Icon, Breadcrumb, Dropdown, Avatar, Spin, Menu } from 'antd';
import { FormattedMessage } from 'umi/locale';
import styles from './Header.less';
import SelectLang from '@/components/SelectLang';
import Link from 'umi/link';
import { routerRedux } from 'dva/router';
import classNames from 'classnames';
// import PageLoading from '@/components/PageLoading';

const { Header } = Layout;

class HeaderView extends PureComponent {

  toggle = () => {
    const { collapsed, onCollapse } = this.props;
    onCollapse(!collapsed);
  }

  getParent = (breadcrumbNameMap, path) => {
    let parent = undefined;
    try {
      breadcrumbNameMap.map(item => {
        if (item.children && item.children.length > 0) {
          item.children.map(child => {
            if (child.path === path) {
              parent = item;
              throw new Error('EndIterative');
            }
            return child;
          });
        }
        return item;
      });
    } catch { }
    return parent;
  };

  itemsRender = (breadcrumbNameMap, path) => {
    let items = [];
    const itemRender = (breadcrumbNameMap, path) => {
      breadcrumbNameMap.forEach(item => {
        if (item.path === path && path !== '/home') {
          items.unshift(item.icon ?
            (<Breadcrumb.Item key={item.path}><Icon type={item.icon} /><span style={{ marginLeft: '5px' }}>{item.name}</span></Breadcrumb.Item>)
            : (<Breadcrumb.Item key={item.path}>{item.name}</Breadcrumb.Item>));
          const parent = this.getParent(breadcrumbNameMap, path);
          if (parent) {
            itemRender(breadcrumbNameMap, parent.path);
          }
        }
      });
    };
    itemRender(breadcrumbNameMap, path);
    return items;
  };

  renderBreadcrumb = () => {
    const { breadcrumbNameMap, location } = this.props;
    if (breadcrumbNameMap && breadcrumbNameMap.length > 0) {
      const home = breadcrumbNameMap.filter(item => item.path === '/home')[0];
      const items = this.itemsRender(breadcrumbNameMap, location.pathname);

      return (
        <Breadcrumb className={styles.bread} separator='>'>
          {home ? (
            <Breadcrumb.Item key={home.path}>
              <Link to='/'>
                {home.icon ? (<Icon type={home.icon} />) : null}
                <span style={{ marginLeft: '5px' }}>{home.name}</span>
              </Link>
            </Breadcrumb.Item>
          ) : null}
          {items}
        </Breadcrumb>
      );
    }
  };

  handleMenuClick = ({ key }) => {
    const { dispatch } = this.props;
    if (key === 'userCenter') {
      routerRedux.push('/account/center');
      return;
    }
    if (key === 'userinfo') {
      routerRedux.push('/account/settings/base');
      return;
    }
    if (key === 'logout') {
      dispatch({
        type: 'login/logout',
      });
    }
  };

  renderCurrentUser = () => {
    const { overlayClassName, currentUser } = this.props;

    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.handleMenuClick}>
        <Menu.Item key="userCenter">
          <Icon type="user" />
          <FormattedMessage id="menu.account.center" defaultMessage="Account Center" />
        </Menu.Item>
        <Menu.Item key="userinfo">
          <Icon type="setting" />
          <FormattedMessage id="menu.account.settings" defaultMessage="Account Settings" />
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="Logout" />
        </Menu.Item>
      </Menu>
    );

    return currentUser && currentUser.username ? (
      <Dropdown overlay={menu} overlayClassName={classNames(styles.container, overlayClassName)}>
        <span className={`${styles.action} ${styles.account}`}>
          {currentUser.avatar ? (
            <Avatar
              size="small"
              className={styles.avatar}
              src={currentUser.avatar}
              alt="avatar"
            />
          ) : null}
          <span className={styles.name}>{currentUser.username}</span>
        </span>
      </Dropdown>
    ) : (
        <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
      );
  };

  render() {
    const { collapsed } = this.props;
    const { overlayClassName, currentUser } = this.props;

    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.handleMenuClick}>
        <Menu.Item key="userCenter">
          <Icon type="user" />
          <FormattedMessage id="menu.account.center" defaultMessage="Account Center" />
        </Menu.Item>
        <Menu.Item key="userinfo">
          <Icon type="setting" />
          <FormattedMessage id="menu.account.settings" defaultMessage="Account Settings" />
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="Logout" />
        </Menu.Item>
      </Menu>
    );
    return (
      <Header className={styles.head} style={{ background: '#fff', padding: 0 }} >
        <div className={styles.left}>
          <Icon
            className={styles.trigger}
            type={collapsed ? 'menu-unfold' : 'menu-fold'}
            onClick={this.toggle}
          />
          {this.renderBreadcrumb()}
        </div>
        <div className={styles.right}>
          {/* {this.renderCurrentUser()} */}
          {currentUser && currentUser.username ? (
            <Dropdown overlay={menu} overlayClassName={classNames(styles.container, overlayClassName)}>
              <span className={`${styles.action} ${styles.account}`}>
                <Avatar
                  size="small"
                  className={styles.avatar}
                  icon="user"
                  alt="avatar"
                />
                <span className={styles.name}>{currentUser.username}</span>
              </span>
            </Dropdown>
          ) : (
              <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
            )}
          <SelectLang className={styles.action} />
        </div>
      </Header>
    );
  }
}

export default connect(({ login: loginModel }) => ({
  currentUser: loginModel.currentUser,
}))(props => (
  <HeaderView {...props} />
));
